import React, { useRef, useEffect, useState } from "react";
import { NavBar } from "react-vant";
import { Notify } from "react-vant";
import { useNavigate } from "react-router-dom";
import { Button } from "react-vant";
import { IconFont } from "tdesign-icons-react";
import axios from "axios";
import './ybk.css'
export default function Face() {
	let navigate = useNavigate();
	useEffect(() => {
		startCamera();
	}, []);
	const videoRef = useRef(null);
	const canvasRef = useRef(null);
	const [capturedImages, setCapturedImages] = useState([]);
	const startCamera = async () => {
		const stream = await navigator.mediaDevices.getUserMedia({ video: true });
		videoRef.current.srcObject = stream;
	};
	const capture = () => {
		console.log('wode');
		const canvas = canvasRef.current;
		const context = canvas.getContext("2d");
		context.drawImage(videoRef.current, 0, 0, canvas.width, canvas.height);
		const imageSrc = canvas.toDataURL("image/jpeg");
		console.log(imageSrc);
		setCapturedImages([...capturedImages, imageSrc]);
		submitImages(imageSrc);

	};
	let submitImages = async (img) => {
		await axios.post("http://localhost:3000/ybk/facelogin", { b64: img }).then((res) => {
			console.log(res)
			if (res.data.code === 200) {
				let { data, Accesstoken, Refreshtoken } = res.data;
				sessionStorage.setItem("info", JSON.stringify(data));
				Notify.show({ type: "success", message: "登录成功" });
				localStorage.setItem("accessToken", Accesstoken);
				localStorage.setItem("refreshToken", Refreshtoken);
				localStorage.setItem('user', JSON.stringify(data));

				navigate('/index')
			} else {
				Notify.show({ type: "danger", message: "登录失败" });
			}
		});
	};
	return (
		<div>
			{/* <div>
				<NavBar onClickLeft={() => navigate(-1)} />
			</div> */}
			<p style={{ fontSize: "3rem", fontWeight: "300", margin: "3rem 1rem", marginLeft: '5rem' }}>人脸识别登录</p>

			<div id='up-password-box'></div>
			<div className="face">
				<video ref={videoRef} autoPlay style={{ width: "35rem", height: "50rem" }} className='tu' />
			</div>
			<canvas ref={canvasRef} style={{ display: "none" }} />
			<div>
				<Button type='primary' style={{ background: "#09bb07" }} className='primary' onClick={capture}>
					登录
				</Button>
			</div>
			<div className="ljyother">
				<div>
					<button className="ljyqi">其他方式登录</button>
				</div>
				<div className="ljybox">
					<div onClick={() => Navigate("/face")}>
						<IconFont name="scan" />
					</div>
					<div onClick={() => Navigate("/code")}>
						<IconFont name="mobile" />
					</div>
				</div>
			</div>
		</div>
	);
}
